<?php

class NewController extends Controller{

    private $M_news;
    private $M_categorys;
    private $M_sources;
    private $M_tags;
    private $M_taghasnews;
    private $M_categoryhastags;

    /**
     * 构造方法
     * 初始化
     */
    public function __construct(){
        $this->M_news = Model::getInstance('news');
        $this->M_categorys = Model::getInstance('categorys');
        $this->M_sources = Model::getInstance('sources');
        $this->M_tags = Model::getInstance('tags');
        $this->M_taghasnews = Model::getInstance('tag has news');
        $this->M_categoryhastags = Model::getInstance('category has tags');
    }

    //模块首页
    public function index(){
        global $controller;
        global $config_arr;

        $curr_page = (int)$this->input()->post('pageNum',1);
        $per_page  = (int)$this->input()->post('numPerPage',30);
        $title = $this->input()->post('title');
        $status = $this->input()->post('status');
        $category_id = $this->input()->post('category_id');
        $source_id = $this->input()->post('source_id');
        $p_stime = $this->input()->post('p_stime');
        $p_etime = $this->input()->post('p_etime');
        $u_stime = $this->input()->post('u_stime');
        $u_etime = $this->input()->post('u_etime');
        $filter = array();

        if($title){
            $filter['title'] = $title;
        }

        if($status){
            $filter['status'] = $status;
        }

        if($category_id){
            $filter['category_id'] = $category_id;
        }

        if($source_id){
            $filter['source_id'] = $source_id;
        }

        if($p_stime){
            $filter['p_stime'] = $p_stime;
        }

        if($p_etime){
            $filter['p_etime'] = $p_etime;
        }

        if($u_stime){
            $filter['u_stime'] = $u_stime;
        }

        if($u_etime){
            $filter['u_etime'] = $u_etime;
        }

        $category_list = $this->M_categorys->getCategorys(null,true);
        $source_list = $this->M_sources->getSources(null,true);

        $list = $this->M_news->getNewList($curr_page,$per_page,$filter);

        $data = array(
            'controller'=>$controller,
            'list'=>$list,
            'category_list'=>$category_list,
            'source_list'=>$source_list,
            'status_list'=>$config_arr['status']['name'],
            'status_color_list'=>$config_arr['status']['font_color']
        );

        Template::show('new/index.php',$data);
    }

    //添加
    public function add(){
        global $controller;
        global $config_arr;

        $category_list = $this->M_categorys->getCategorys(null,true);
        $source_list = $this->M_sources->getSources(null,true);

        $data = array(
            'controller'=>$controller,
            'category_list'=>$category_list,
            'source_list'=>$source_list,
            'status_list'=>$config_arr['status']['name']
        );

        Template::show('new/add.php',$data);
    }

    //删除
    public function del(){
        $new_id = $this->input()->get('new_id');

        $info = $this->M_news->get($new_id);

		if(!empty($info)){

			$focus_image_path = explode('Upload',$info['picture']);

			$focus_image_path = DOCUMENT_ROOT_PATH . 'Upload' . $focus_image_path[1];
	
			if(file_exists($focus_image_path)){
			   if(!unlink($focus_image_path)){
					$data = array(
						"statusCode"=>"300",
						"message"=>"删除文章焦点图片失败",
					);
					echo Response::JSON(300,$data);
					exit;
			   }
			}

			$preImg = "/<[i|I][m|M][g|G].*?src=[\'|\"](.*?(?:[\.gif|\.jpg|\.png|\.bmp|\.jpeg]))[\'|\"].*?[\/]?>/";

			preg_match_all($preImg, $info['content'], $str_arr); //$content为原始文章内容，下同

			$check_unlink_image = true;
			foreach ($str_arr[1] as $v) {

				$image_path = explode('Upload',$v);

				$image_path = DOCUMENT_ROOT_PATH . 'Upload' . $image_path[1];

				if(file_exists($image_path)){
				   if(!unlink($image_path)){
					   $check_unlink_image = false;
				   }
				}

				$small_image_path = str_replace('big','small',$image_path);

				if(file_exists($small_image_path)){
				   if(!unlink($small_image_path)){
					   $check_unlink_image = false;
				   }
				}

			}
		}

		if(!$check_unlink_image){
			$data = array(
                "statusCode"=>"300",
                "message"=>"删除文章内容图片失败",
            );
            echo Response::JSON(300,$data);
			exit;
		}


        $ret = $this->M_news->delNew($new_id);

        if($ret){
            $data = array(
                "statusCode"=>"200",
                "message"=>"删除成功",
                "navTabId"=>"new"
            );
            $this->M_taghasnews->delByNewId($new_id);
            echo Response::JSON(200,$data);
        }else{

            $data = array(
                "statusCode"=>"300",
                "message"=>"删除失败",
            );
            echo Response::JSON(300,$data);
        }
    }

    //修改
    public function edit(){
        global $controller;
        global $config_arr;

        $new_id = $this->input()->get('new_id');

        $info = $this->M_news->get($new_id);

        $category_list = $this->M_categorys->getCategorys(null,true);
        $source_list = $this->M_sources->getSources(null,true);

        $data = array(
            'controller'=>$controller,
            'info'=>$info,
            'category_list'=>$category_list,
            'source_list'=>$source_list,
            'status_list'=>$config_arr['status']['name']
        );

        Template::show('new/edit.php',$data);
    }

    //修改资讯为推荐状态
    public function recommend(){
        $type = $this->input()->get('type');
        $new_id = $this->input()->get('new_id');

        if(!$new_id || !in_array($type,array('index','list'))){
            $data = array(
                "statusCode"=>"300",
                "message"=>"参数错误,推荐资讯编号或者类型不存在！",
            );
            echo Response::JSON(300,$data);
            exit;
        }

        $status = '';
        $flag = '';
        switch($type){
            case 'index':
                $status = 5;
                $flag = '首页';
                break;
            case 'list':
                $status = 4;
                $flag = '列表页';
                break;
        }

        if($status == ''){
            $data = array(
                "statusCode"=>"300",
                "message"=>"参数错误,推荐类型错误！",
            );
            echo Response::JSON(300,$data);
            exit;
        }

        $ret = $this->M_news->recommendNew($new_id,$status);

        if($ret){
            $data = array(
                "statusCode"=>"200",
                "message"=>"推荐资讯到".$flag."成功",
                "navTabId"=>"new"
            );
            echo Response::JSON(200,$data);
        }else{

            $data = array(
                "statusCode"=>"300",
                "message"=>"推荐资讯到".$flag."失败",
            );
            echo Response::JSON(300,$data);
        }
    }

    //异步添加
    public function ajaxAdd(){

        $category_id = $this->input()->post('category_id');
        $source_id = $this->input()->post('source_id');
        $title = $this->input()->post('title');
        $keywords = $this->input()->post('keywords');
        $description = $this->input()->post('description');
        $status = $this->input()->post('status');
        $summary = $this->input()->post('summary');
        $content = $this->input()->post('content');
        $tag = $this->input()->post('tag','new');
        $picture = $this->input()->post('picture');
        $user_id = $this->session()->get('user_id',rand(13698,13714));

        if(!$category_id || !$source_id || !$title || !$keywords || !$description || !$status || !$summary || !$content || !$tag || !$picture || !$user_id ){
            $data = array(
                "statusCode"=>"300",
                "message"=>"参数错误，请填写完入库表单！",
            );
            echo Response::JSON(300,$data);
            exit;
        }

        $ret = $this->M_news->addNew($category_id, $source_id, $title, $keywords, $description, $status, $summary, $content, $tag, $picture, $user_id);
        if($ret){

            $data = array(
                "statusCode"=>"200",
                "message"=>"添加成功",
                "navTabId"=>"new",
                "callbackType"=>"closeCurrent"
            );
            //标签 与 新闻 及 分类 的关联操作 $category_id 分类ID  $result 新闻ID
            $tag_arr = explode(',',$tag);

            foreach((array)$tag_arr as $k=>$v){
                $tag_id = $this->M_tags->addTag($v);

                if($tag_id){
                    //标签关联新闻
                    $this->M_taghasnews->addTagHasNews($tag_id,$ret);
                    //分类关联标签
                    $this->M_categoryhastags->addCategoryHasTags($category_id,$tag_id);
                }
            }

            echo Response::JSON(200,$data);
        }else{

            $data = array(
                "statusCode"=>"300",
                "message"=>"添加失败",
            );
            echo Response::JSON(300,$data);
        }
        exit;
    }

    //异步添加
    public function ajaxEdit(){

        $new_id = $this->input()->post('new_id');
        $category_id = $this->input()->post('category_id');
        $old_category_id = $this->input()->post('old_category_id');
        $source_id = $this->input()->post('source_id');
        $title = $this->input()->post('title');
        $keywords = $this->input()->post('keywords');
        $description = $this->input()->post('description');
        $status = $this->input()->post('status');
        $summary = $this->input()->post('summary');
        $content = $this->input()->post('content');
        $tag = $this->input()->post('tag');
        $old_tag = $this->input()->post('old_tag');
        $picture = $this->input()->post('picture');

        if(!$new_id || !$category_id || !$old_category_id || !$source_id || !$title || !$keywords || !$description || !$status || !$summary || !$content || !$tag || !$old_tag || !$picture){
            $data = array(
                "statusCode"=>"300",
                "message"=>"参数错误，请填写完入库表单！",
            );
            echo Response::JSON(300,$data);
            exit;
        }

        $ret = $this->M_news->editNew($new_id, $category_id, $source_id, $title, $keywords, $description, $status, $summary, $content, $tag, $picture);

        if($ret){

            $data = array(
                "statusCode"=>"200",
                "message"=>"编辑成功",
                "navTabId"=>"new",
                "callbackType"=>"closeCurrent"
            );
            //标签关联属性修改
            $tag_arr = explode(',',$tag);
            $old_tag_arr = explode(',',$old_tag);

            //添加新标签关联操作
            $add_tag_arr= my_array_diff($tag_arr,$old_tag_arr);

            foreach((array)$add_tag_arr as $k=>$v){
                $tag_info = $this->M_tags->getTagInfoByName($v);

                if($tag_info){
                    //标签关联新闻
                    $this->M_taghasnews->addTagHasNews($tag_info['tag_id'],$new_id);
                    //分类关联标签
                    $this->M_categoryhastags->addCategoryHasTags($category_id,$tag_info['tag_id']);
                }
            }
            //删除标签关联操作
            $del_tag_arr= my_array_diff($tag_arr,$add_tag_arr);

            foreach((array)$del_tag_arr as $k=>$v){
                $tag_info = $this->M_tags->getTagInfoByName($v);

                if($tag_info){
                    //标签关联新闻
                    $this->M_taghasnews->delByNewIDAndTagID($new_id,$tag_info['tag_id']);
                    //分类关联标签
                    $this->M_categoryhastags->delByCategoryIdAndTagID($old_category_id,$tag_info['tag_id']);
                }
            }
            //修改标签所属分类
            if($category_id != $old_category_id){
                $change_tag_arr = my_array_diff($tag_arr,$del_tag_arr);
                foreach((array)$change_tag_arr as $k=>$v){
                    $tag_info = $this->M_tags->getTagInfoByName($v);
                    if($tag_info){
                        //分类关联标签
                        $this->M_categoryhastags->updateCategoryHasTags($category_id,$old_category_id,$tag_info['tag_id']);
                    }
                }
            }

            echo Response::JSON(200,$data);
        }else{

            $data = array(
                "statusCode"=>"300",
                "message"=>"编辑失败",
            );
            echo Response::JSON(300,$data);
        }
        exit;
    }

    /**
     * 新闻 缩图 上传
     */
    public function newPictureUpload(){
        $type = $this->input()->get('type','focus');
        $ret = uploadFile($type);

        if($ret['statusCode'] == 2){//上传成功
            $img_ret = explode('Upload',  $ret['data'][0]['savepath'].$ret['data'][0]['savename']);
            if($type == 'new'){
                echo json_encode(array('error'=>0, 'url'=>'/Upload' . $img_ret[1]));

            }else{
                echo '/Upload' . $img_ret[1];
            }
        }else{
            echo 'error#'.$ret['data'][0];
        }
    }

    public function newDirPicture(){
        //根目录路径，可以指定绝对路径，比如 /var/www/attached/
        $root_path = DOCUMENT_ROOT_PATH . 'Upload/';
        //根目录URL，可以指定绝对路径，比如 http://www.yoursite.com/attached/
        $root_url = getHttpHost().'/Upload/';
        //图片扩展名
        $ext_arr = array('gif', 'jpg', 'jpeg', 'png', 'bmp');

        //根据path参数，设置各路径和URL
        if (empty($_GET['path'])) {
            $current_path = realpath($root_path) . '/';
            $current_url = $root_url;
            $current_dir_path = '';
            $moveup_dir_path = '';
        } else {
            $current_path = realpath($root_path) . '/' . $_GET['path'];
            $current_url = $root_url . $_GET['path'];
            $current_dir_path = $_GET['path'];
            $moveup_dir_path = preg_replace('/(.*?)[^\/]+\/$/', '$1', $current_dir_path);
        }
        //排序形式，name or size or type
        $order = empty($_GET['order']) ? 'name' : strtolower($_GET['order']);

        //不允许使用..移动到上一级目录
        if (preg_match('/\.\./', $current_path)) {
            echo 'Access is not allowed.';
            exit;
        }
        //最后一个字符不是/
        if (!preg_match('/\/$/', $current_path)) {
            echo 'Parameter is not valid.';
            exit;
        }
        //目录不存在或不是目录
        if (!file_exists($current_path) || !is_dir($current_path)) {
            echo 'Directory does not exist.';
            exit;
        }

        //遍历目录取得文件信息
        $file_list = array();
        if ($handle = opendir($current_path)) {
            $i = 0;
            while (false !== ($filename = readdir($handle))) {
                if ($filename{0} == '.') continue;
                $file = $current_path . $filename;
                if (is_dir($file)) {
                    $file_list[$i]['is_dir'] = true; //是否文件夹
                    $file_list[$i]['has_file'] = (count(scandir($file)) > 2); //文件夹是否包含文件
                    $file_list[$i]['filesize'] = 0; //文件大小
                    $file_list[$i]['is_photo'] = false; //是否图片
                    $file_list[$i]['filetype'] = ''; //文件类别，用扩展名判断
                } else {
                    $file_list[$i]['is_dir'] = false;
                    $file_list[$i]['has_file'] = false;
                    $file_list[$i]['filesize'] = filesize($file);
                    $file_list[$i]['dir_path'] = '';
                    $file_ext = strtolower(array_pop(explode('.', trim($file))));
                    $file_list[$i]['is_photo'] = in_array($file_ext, $ext_arr);
                    $file_list[$i]['filetype'] = $file_ext;
                }
                $file_list[$i]['filename'] = $filename; //文件名，包含扩展名
                $file_list[$i]['datetime'] = date('Y-m-d H:i:s', filemtime($file)); //文件最后修改时间
                $i++;
            }
            closedir($handle);
        }

        //排序
        usort($file_list, 'cmpNewDirPicture');

        $result = array();
        //相对于根目录的上一级目录
        $result['moveup_dir_path'] = $moveup_dir_path;
        //相对于根目录的当前目录
        $result['current_dir_path'] = $current_dir_path;
        //当前目录的URL
        $result['current_url'] = $current_url;
        //文件数
        $result['total_count'] = count($file_list);
        //文件列表数组
        $result['file_list'] = $file_list;
        //输出JSON字符串
        echo Response::Default_JSON(0,$result);
    }

    public function getTags(){
        $title = $this->input()->get('title');

        $ret = strToTags($title);

        echo Response::Default_JSON(0,$ret);
    }
}